package cn.org.rookie.jeesdp.file.contreller;

import cn.org.rookie.jeesdp.core.BusinessException;
import cn.org.rookie.jeesdp.core.utils.IOUtils;
import cn.org.rookie.jeesdp.file.service.FileService;
import cn.org.rookie.jeesdp.web.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;

@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping("upload")
    public Response upload(MultipartFile file) {
        try {
            return Response.success().data(fileService.store(file.getInputStream(), file.getOriginalFilename(),
                    MediaTypeFactory.getMediaTypes(file.getName()).getFirst().getType()));
        } catch (IOException e) {
            throw new BusinessException(0, "文件上传错误！", e);
        }
    }

    @RequestMapping("delete/{id}")
    public Response delete(@PathVariable String id) {
        fileService.delete(id);
        return Response.success();
    }

    @RequestMapping("download/{id}/{name}")
    public ResponseEntity<StreamingResponseBody> download(@PathVariable String id, @PathVariable String name) {
        GridFsResource resource = fileService.getResource(id);

        StreamingResponseBody body = response -> {
            IOUtils.copy(resource.getInputStream(), response);
            IOUtils.closeQuietly(response);
        };

        return ResponseEntity.ok()
                .header(
                        HttpHeaders.CONTENT_DISPOSITION,
                        ContentDisposition.attachment()
                                .filename(name != null && !name.isEmpty() ? name : resource.getFilename())
                                .build()
                                .toString()
                ).body(body);
    }

    @RequestMapping("download/{id}")
    public ResponseEntity<StreamingResponseBody> download(@PathVariable String id) {
        return download(id, null);
    }
}
